import cv2
import glob
import os
import numpy as np

for img_dir in glob.glob(os.path.join(r'F:\work_dir\project\matchTemplate\week3\Test', '*')):

    src_img = cv2.imread(img_dir)
    gray = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)
    cv2.imshow("gray", gray)
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    cv2.imshow('binary', binary)
    contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    # =====对边缘进行分析，要有一定大小，有一定比例才是符合要求的====
    temp_contours = []
    if len(contours) > 0:
        for contour in contours:
            if cv2.contourArea(contour) > 100:
                temp_contours.append(contour)
            car_plates = []
            for temp_contour in temp_contours:
                rect_tupple = cv2.minAreaRect(temp_contour)
                rect_width, rect_height = rect_tupple[1]
                if rect_width < rect_height:
                    rect_width, rect_height = rect_height, rect_width
                aspect_ratio = rect_width / rect_height
                # 车牌正常情况下宽高比在2 - 5.5之间
                if 2 < aspect_ratio < 5.5:
                    car_plates.append(temp_contour)
                    rect_vertices = cv2.boxPoints(rect_tupple)
                    rect_vertices = np.int0(rect_vertices)   # 矩形的四个角点取整
            # if len(car_plates) == 1:
            #     oldimg = cv2.drawContours(img, [rect_vertices], -1, (0, 0, 255), 2)
            #     # cv2.imshow("che pai ding wei", oldimg)
            #     # print(rect_tupple)
            #     break
    cv2.drawContours(src_img, temp_contours, contourIdx=-1, color=(0, 0, 255),
                     thickness=None, lineType=None, hierarchy=None, maxLevel=None, offset=None)

    cv2.imshow("img", src_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
